import { Injectable } from '@nestjs/common';
import { Filter, FilterOperate } from './filter-group';
import { PageCondition } from './page-condition';
import { Equal, Like, In, LessThan, LessThanOrEqual, MoreThan, MoreThanOrEqual, Not } from 'typeorm';

// 分页条件查询
@Injectable()
export class PageRequest {
  filter: Filter;
  pageCondition: PageCondition;
  // 构造符合 typeOrm 的查询条件
  genQueryCondition(filter: Filter) {
    const { rules, groups } = filter;
    const where: Record<string, any> = {};

    if (rules.length) {
      rules.forEach((rule) => {
        const { field, value, operate } = rule;
        switch (operate) {
          case FilterOperate.EQUAL_TO:
            where[field] = Equal(value);
            break;

          case FilterOperate.NOT_EQUAL_TO:
            where[field] = Not(Equal(value));

          case FilterOperate.LESS_THAN:
            where[field] = LessThan(value);
            break;

          case FilterOperate.LESS_THAN_EQUAL_TO:
            where[field] = LessThanOrEqual(value);
            break;

          case FilterOperate.GREATER_THAN:
            where[field] = MoreThan(value);
            break;

          case FilterOperate.GREATER_THAN_EQUAL_TO:
            where[field] = MoreThanOrEqual(value);
            break;

          case FilterOperate.START_AT:
            where[field] = Like(`%${value}`);
            break;

          case FilterOperate.END_AT:
            where[field] = Like(`${value}%`);
            break;

          case FilterOperate.CONTAIN:
            where[field] = Like(`%${value}%`);
            break;

          case FilterOperate.NOT_CONTAIN:
            where[field] = Not(Like(`%${value}%`));
            break;

          default:
            break;
        }
      });
    }

    return where;
  }
}
